package com.tw.persistence;

import java.util.ArrayList;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import org.hibernate.sql.Select;

import javax.persistence.Query;
import javax.persistence.criteria.From;
import org.hibernate.criterion.Restrictions;

//import com.sun.tools.javac.util.List;

public class UserController {
	
	public void save(String name, String email, String password) throws Exception {
		
		 AnnotationConfiguration config = new AnnotationConfiguration();
		 config.addAnnotatedClass(User.class);
		 config.configure(); 
		 
		 User user = new User();
		 user.setName(name);
		 user.setEmail(email);
		 user.setPassword(password);
		 
		 SessionFactory sessionFactory = config.configure().buildSessionFactory();
		 Session session = sessionFactory.getCurrentSession();

		 session.beginTransaction();
		 session.save(user);
		 session.getTransaction().commit();

    }

	public void update(String name, String email, String password) throws Exception {
		
		 AnnotationConfiguration config = new AnnotationConfiguration();
		 config.addAnnotatedClass(User.class);
		 config.configure(); 
		 
		 SessionFactory sessionFactory = config.configure().buildSessionFactory();
		 Session session = sessionFactory.getCurrentSession();
		 session.beginTransaction();
		 ArrayList users = (ArrayList) session.createCriteria(User.class)
		    .add( Restrictions.like("name", name))
		    .list();
		 
		 User user = (User)users.get(0);
		 user.setEmail(email);
		 user.setPassword(password);
		 
		 session.update(user);
		 session.getTransaction().commit();
		 
		}
	
	public static void main(String args[]){
		try{
			(new UserController()).save("test", "test", "test");
		} catch(Exception e){
			
		}
	}
	 
}
